import "./index.css";

const className = "mask-loading-container";

// 全局 单例模式
const initGlobalMask = () => {
  const globalMask = document.createElement("div");
  globalMask.classList.add(className);
  globalMask.classList.add("wh-100");
  globalMask.classList.add("center");
  globalMask.style.backgroundColor = `rgba(100, 100, 100, 0.5)`;
  globalMask.style.position = "fixed";
  globalMask.style.zIndex = 9999;
  globalMask.style.top = 0;
  globalMask.style.left = 0;
  globalMask.style.display = "none"; // 默认隱藏
  document.body.appendChild(globalMask);

  const loadingMask = document.createElement("div");
  loadingMask.classList.add("loading-mask");
  globalMask.appendChild(loadingMask);

  return globalMask;
};

const globalMask = initGlobalMask();

const initSubMask = (parent) => {
  parent = typeof parent === "string" ? document.querySelector(parent) : parent;
  parent.style.position = "relative";

  const subMask = parent.querySelector(`.${className}`);

  if (subMask) {
    return subMask;
  } else {
    const subMask = document.createElement("div");
    subMask.classList.add(className);
    subMask.classList.add("wh-100");
    subMask.classList.add("center");
    subMask.style.backgroundColor = `rgba(100, 100, 100, 0.5)`;
    subMask.style.position = "absolute";
    subMask.style.zIndex = 9999;
    subMask.style.top = 0;
    subMask.style.left = 0;
    subMask.style.display = "none"; // 默认隱藏
    parent.appendChild(subMask);

    const loadingMask = document.createElement("div");
    loadingMask.classList.add("loading-mask");
    subMask.appendChild(loadingMask);

    return subMask;
  }
};

/**
 * 增加 Loading 动画
 *
 * 注：本函数会将 施加loading动画的 DOM元素的 position 设置为 `relative`;
 *
 * @param {Boolean} flag flag 为 true，则页面显示 加载动画； flag 为 false，则页面 取消加载动画。
 * @param {String | Element} [selector] 可选参；指定DOM元素的css选择器；
 *  若有该选择器，则给指定 DOM元素增加loading动画；没有该参数，则是全页面loading动画
 */
export function loading(flag, selector) {
  if (selector) {
    const subMask = initSubMask(selector);
    if (flag) {
      subMask.style.display = "flex";
    } else {
      subMask && subMask.remove();
    }
  } else {
    globalMask.style.display = flag ? "flex" : "none";
  }
}
